package com.example.oracleviewer.controller;

import com.example.oracleviewer.entity.UserCard;
import com.example.oracleviewer.service.UserCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户卡片控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/usercards")
@CrossOrigin(origins = "*")
public class UserCardController {
    
    @Autowired
    private UserCardService userCardService;
    
    /**
     * 查询所有用户卡片数据
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllUserCards() {
        log.info("接收到查询所有用户卡片的请求");
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<UserCard> userCards = userCardService.getAllUserCards();
            
            // 打印指定userNumb的数据
            log.info("=== 打印指定userNumb的数据 ===");
//            for (UserCard card : userCards) {
//                if ("1820".equals(card.getUserId()) || "1790".equals(card.getUserId())) {
//                    log.info("USERID: {}, USERNUMB: {}, USERNAME: {}, UPDATETIME: {}, CREATETIME: {}",
//                        card.getUserId(), card.getUserNumb(), card.getUsername(),
//                        card.getUpdateTime(), card.getCreateTime());
//                }
//            }
            
            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", userCards);
            response.put("count", userCards.size());
            log.info("成功返回 {} 条用户卡片数据", userCards.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("查询所有用户卡片失败", e);
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据用户ID查询
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserCardByUserId(@PathVariable String userId) {
        log.info("接收到根据用户ID查询的请求: {}", userId);
        Map<String, Object> response = new HashMap<>();
        
        try {
            UserCard userCard = userCardService.getUserCardByUserId(userId);
            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", userCard);
            log.info("成功返回用户卡片数据");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据用户ID查询失败", e);
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据更新时间查询（大于指定时间）
     */
    @GetMapping("/updatetime")
    public ResponseEntity<Map<String, Object>> getUserCardsByUpdateTime(@RequestParam String time) {
        log.info("接收到按更新时间查询的请求: time={}", time);
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<UserCard> userCards = userCardService.getUserCardsByUpdateTime(time);
            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", userCards);
            response.put("count", userCards.size());
            log.info("成功返回 {} 条用户卡片数据", userCards.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("按更新时间查询失败", e);
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据用户编号查询
     */
    @GetMapping("/usernumb/{userNumb}")
    public ResponseEntity<Map<String, Object>> getUserCardsByUserNumb(@PathVariable String userNumb) {
        log.info("接收到根据用户编号查询的请求: userNumb={}", userNumb);
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<UserCard> userCards = userCardService.getUserCardsByUserNumb(userNumb);
            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", userCards);
            response.put("count", userCards.size());
            log.info("成功返回 {} 条用户卡片数据", userCards.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据用户编号查询失败", e);
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 调试接口 - 测试时间查询
     */
    @GetMapping("/debug/time")
    public ResponseEntity<Map<String, Object>> debugTimeQuery(@RequestParam String time) {
        log.info("接收到调试时间查询的请求: time={}", time);
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 先查询所有数据，看看时间字段的格式
            List<UserCard> allCards = userCardService.getAllUserCards();
            List<UserCard> timeFilteredCards = userCardService.getUserCardsByUpdateTime(time);
            List<UserCard> timeFilteredCardsTimestamp = userCardService.getUserCardsByUpdateTimeTimestamp(time);
            
            response.put("success", true);
            response.put("message", "调试查询成功");
            response.put("allDataCount", allCards.size());
            response.put("timeFilteredCount", timeFilteredCards.size());
            response.put("timeFilteredCountTimestamp", timeFilteredCardsTimestamp.size());
            response.put("timeFilteredData", timeFilteredCards);
            response.put("timeFilteredDataTimestamp", timeFilteredCardsTimestamp);
            
            // 显示前5条数据的时间格式
            if (!allCards.isEmpty()) {
                List<Map<String, Object>> sampleData = allCards.stream()
                    .limit(5)
                    .map(card -> {
                        Map<String, Object> sample = new HashMap<>();
                        sample.put("userId", card.getUserId());
                        sample.put("userNumb", card.getUserNumb());
                        sample.put("updateTime", card.getUpdateTime());
                        sample.put("createTime", card.getCreateTime());
                        return sample;
                    })
                    .collect(java.util.stream.Collectors.toList());
                response.put("sampleData", sampleData);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("调试时间查询失败", e);
            response.put("success", false);
            response.put("message", "调试查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 调试接口 - 打印指定userNumb的数据
     */
    @GetMapping("/debug/usernumb")
    public ResponseEntity<Map<String, Object>> debugUserNumbData() {
        log.info("接收到调试userNumb数据的请求");
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 查询指定的userNumb数据
            List<UserCard> userCards1234567 = userCardService.getUserCardsByUserNumb("1234567");
            List<UserCard> userCards100447 = userCardService.getUserCardsByUserNumb("100447");
            
            // 打印到控制台
            log.info("=== userNumb: 1234567 的数据 ===");
            if (!userCards1234567.isEmpty()) {
                for (UserCard card : userCards1234567) {
                    log.info("USERID: {}, USERNUMB: {}, USERNAME: {}, UPDATETIME: {}, CREATETIME: {}", 
                        card.getUserId(), card.getUserNumb(), card.getUsername(), 
                        card.getUpdateTime(), card.getCreateTime());
                }
            } else {
                log.info("未找到userNumb为1234567的数据");
            }
            
            log.info("=== userNumb: 100447 的数据 ===");
            if (!userCards100447.isEmpty()) {
                for (UserCard card : userCards100447) {
                    log.info("USERID: {}, USERNUMB: {}, USERNAME: {}, UPDATETIME: {}, CREATETIME: {}", 
                        card.getUserId(), card.getUserNumb(), card.getUsername(), 
                        card.getUpdateTime(), card.getCreateTime());
                }
            } else {
                log.info("未找到userNumb为100447的数据");
            }
            
            response.put("success", true);
            response.put("message", "调试查询成功，请查看控制台日志");
            response.put("userNumb1234567Count", userCards1234567.size());
            response.put("userNumb100447Count", userCards100447.size());
            response.put("userNumb1234567Data", userCards1234567);
            response.put("userNumb100447Data", userCards100447);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("调试userNumb数据查询失败", e);
            response.put("success", false);
            response.put("message", "调试查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("message", "Oracle Viewer服务运行正常");
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }
} 